﻿/*
 * Created by SharpDevelop.
 * User: wxm
 * Date: 2014/1/18
 * Time: 0:23
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;
using System.CodeDom.Compiler;
using AppConfig;

namespace AllInOne
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();						
		}
		
		void WbMainDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
            page = new HomePage(wbMain.Document);

			foreach (var filename in CSharpApp.AppList.Select(a=>a.Location)) {
                page.AddSampleToList(filename, this.LoadSample);
			}

            page.AddRunHandler(this.RunSample);
		}
		
		void MainFormLoad(object sender, EventArgs e)
		{							
			LoadPanel();		                     
		}
		
		void BtnLoadClick(object sender, EventArgs e)
		{
			LoadPanel();
		}
		
		#region Utility
        HomePage page;

		void LoadPanel(){
			wbMain.Url = new Uri(Environment.CurrentDirectory + "\\base.html");	
		}
		
		void LoadSample(string filename){
            var content = CSharpApp.GetContent(filename);
			page.TextContent = content;
			page.LableSample = String.Format("Codes {0}:", filename);
		}

        void RunSample()
        {
            var content = page.TextContent;
            if (String.IsNullOrEmpty(content)) return;

            var p = this.InitProxy();


            DomainManager.Start(page.LableSample).Execute(content, p);
        }

        Proxy InitProxy()
        {
            var proxy = new Proxy();

            proxy.ConsoleWrite = (content, newline) =>
            {
                page.HtmlOutput += content.Replace(" ", "&nbsp;").Replace("\t", "<span class='tab'></span>");
                if (newline) page.HtmlOutput += "<br/>";
            };

            proxy.PromptInput = () =>
            {
                return page.Invoke("prompt", "Please enter the arguments:").ToString();
            };

            return proxy;
        }
		#endregion
	}
}
